package com.example.carmqtt.service;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

/**
 * @author Weizheng Liu
 * @date 2025/4/16 10:47
 * @description
 */
@Service
public class VehicleMqttService {

    @Autowired
    private MqttPahoClientFactory mqttClientFactory;

    @Value("${mqtt.default-topic}")
    private String defaultTopic;

    // 发送指令到指定小车
    public void sendCommand(String vehicleId, String command) {
        try {
            MqttClient client = new MqttClient(
                    mqttClientFactory.getConnectionOptions().getServerURIs()[0],
                    "server-" + vehicleId,
                    new MemoryPersistence()
            );
            client.connect(mqttClientFactory.getConnectionOptions());

            String topic = "vehicles/command/" + vehicleId;
            MqttMessage message = new MqttMessage(command.getBytes());
            message.setQos(1);
            client.publish(topic, message);

            client.disconnect();
        } catch (MqttException e) {
            throw new RuntimeException("MQTT指令发送失败", e);
        }
    }

    // 接收小车状态（通过Spring Integration）
    @ServiceActivator(inputChannel = "mqttInputChannel")
    public void handleStatusMessage(Message<?> message) {
        String topic = message.getHeaders().get("mqtt_receivedTopic").toString();
        String payload = new String((byte[]) message.getPayload());

        System.out.printf("收到小车上报: [主题=%s] %s%n", topic, payload);
        // 这里可以解析payload并更新数据库或触发业务逻辑
    }
}